package com.jiwen.interceptor;

import com.jiwen.util.SessionUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shrstart
 * @create 2023-12-16-8:42
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        if (token == null) {
            response.setStatus(401);
        } else if (SessionUtil.get(token) == null) {

            SessionUtil.remove(token);

            response.setStatus(403);
        } else {

            String[] split = token.split("-");
            if (System.currentTimeMillis() - Long.valueOf(split[1]) > 2 * 3600 * 1000) {
                response.setStatus(403);
            } else {
                return true;
            }
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
